//
//  LJYTabBar.swift
//  新浪微博25
//
//  Created by 李俊扬 on 2017/6/29.
//  Copyright © 2017年 李俊扬. All rights reserved.
//

import UIKit

protocol LJYTabBarDelegate: NSObjectProtocol {
    // 声明协议方法
    func composeButtonSelect()
}

class LJYTabBar: UITabBar {
    
    // 声明闭包
    var closure:(()->())?
    
    // 声明代理
    weak var ljyDelegate: LJYTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }
    
    // 设置视图
    private func setupUI() {
      addSubview(composeButton)
        
    }
    
    // 调整子控件的位置
    override func layoutSubviews() {
        super .layoutSubviews()
        
        // 设置加号按钮的位置
        composeButton.center = CGPoint(x: frame.width / 2, y: frame.height / 2)
        // 计算每一个按钮的宽度
        let childW = frame.size.width * 0.2
        // 记录当前button按钮的位置
        var index = 0
        
        // 遍历子控件
        for childView in subviews {
            
            if childView.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                // 设置按钮的宽
               var frame = childView.frame
                frame.size.width = childW
                // 设置按钮的x
                frame.origin.x = CGFloat(index) * childW
                childView.frame = frame
                
                // index递增
                index += 1
                
                // 遍历发现第2个位置会遍历到"发现",所有应把"发现"往后移动一个位置
                if index == 2 {
                    
                    index += 1
                }
            }
        }
       
    }
    
    @objc private func composeButtonClick() {
    
        ljyDelegate?.composeButtonSelect()
    }
    
    // 懒加载按钮
    lazy var composeButton: UIButton = {
        
        let bottn = UIButton()
        // 监听按钮
        bottn.addTarget(self, action: #selector(composeButtonClick), for: UIControlEvents.touchUpInside)
        
        // 设置按钮不同状态的图片
         bottn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        bottn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal)
        bottn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        bottn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState.normal)
       
        
        // 设置图片大小
        bottn.sizeToFit()
//
        return bottn
    }()

}
